package com.xhy.documents_collection.exception;

import com.xhy.documents_collection.service.sys.SysSettingService;
import com.xhy.documents_collection.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import java.util.StringJoiner;

/**
 * Author: Xhy
 * CreateTime: 2022-06-04 21:24
 * 全局异常捕获类
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {


    @Autowired
    private SysSettingService sysSettingService;


    @ExceptionHandler(value = MultipartException.class)
    public R fileUploadExceptionHandler(MultipartException exception){
        String limitFileSize = String.valueOf(sysSettingService.getById(1).getRequestFileSize()) + "MB";
        return R.error().message("文件太大,文件限制大小为:"+limitFileSize);
    }

    @ExceptionHandler(Exception.class)
    public R exceptionAll(Exception e){
        e.printStackTrace();
        return R.error().message("服务器内部错误");
    }

    @ExceptionHandler(BaseException.class)
    public R doBaseException(BaseException e){
        e.printStackTrace();
        return R.error().message(e.getMsg()).code(e.getCode());
    }

    @ExceptionHandler(OssException.class)
    public R doOssException(BaseException e){
        e.printStackTrace();
        return R.error().message(e.getMsg()).code(e.getCode());
    }



    // 数据校验异常处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R exception(MethodArgumentNotValidException e) {
        // e.getBindingResult()：获取BindingResult
        BindingResult bindingResult = e.getBindingResult();
        // 收集数据校验失败后的信息
        StringJoiner joiner = new StringJoiner(",");

        bindingResult.getFieldErrors().stream().forEach((fieldError) -> {
            joiner.add(fieldError.getDefaultMessage());

        });
        // 响应给前端
        return R.error().message(joiner.toString());
    }
}
